﻿using Microsoft.Data.Sqlite;
using SendMailServer.Database;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;

namespace SendMailServer.User
{
    internal class UserManager
    {
        public static List<MailInfo> MailListItem = new List<MailInfo>();

        #region 加载用户
        public void LoadUserFromFile()
        {
            var fileName = "D:\\Program Files\\SendMailServer\\lastUser.ini";
            if (MailListItem.Count != 0)
            {
                return;
            }
            try
            {
                if (File.Exists(fileName))
                {
                    var lines = System.IO.File.ReadAllLines(fileName);
                    for (var i = 0; i < lines.Length; i++)
                    {
                        var qs = lines[i].Split(',');
                        var emailName = qs[0];
                        var code = qs[1];
                        CultureInfo provider = CultureInfo.InvariantCulture;
                        var time = DateTime.ParseExact(qs[2], "yyyy-MM-dd HH:mm:ss", provider);

                        MailListItem.Add(new MailInfo() { Code = code, EmailName = emailName, LastSendDate = time });
                    }
                }
            }
            catch (Exception err)
            {
                System.IO.File.WriteAllText("D:\\Program Files\\SendMailServer\\log.txt", "初始化MailList失败" + err.Message + "," + err.StackTrace);
            }
        } 
        public void LoadUserFromDB()
        {
            StringBuilder stringBuilder = new StringBuilder();
            Microsoft.Data.Sqlite.SqliteConnection conn = null;
            Microsoft.Data.Sqlite.SqliteCommand cmd = null;
            SqliteDataReader dr = null;
            MailListItem.Clear();
            try
            {
                using (conn = DatabaseHelper.BuildConnection())
                {
                    string sql = "select * from studioUser";
                    cmd = new Microsoft.Data.Sqlite.SqliteCommand(sql, conn);
                    dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        var userName = dr["userName"].ToString();
                        var registTime = dr["registTime"].ToString();
                        var validDays = int.Parse(dr["validDays"].ToString());
                        var validCode = dr["validCode"].ToString();

                        CultureInfo provider = CultureInfo.InvariantCulture;
                        var time = DateTime.ParseExact(registTime, "yyyy-MM-dd HH:mm:ss", provider);

                        MailListItem.Add(new MailInfo() { Code = validCode, EmailName = userName, LastSendDate = time, validDayss = validDays });
                    }
                }
            }
            catch (Exception err)
            {
                Logger.WriteLine("LoadUserFromDB发生异常:" + err.Message+";"+err.StackTrace);
            }
            finally
            {
                if (dr != null)
                {
                    dr.Close();
                }
                if (cmd != null)
                {
                    cmd.Dispose();
                }
                if (conn != null)
                {
                    conn.Close();
                    conn.Dispose();
                }
            }
        }
        #endregion

        #region 添加用户
        public ResMsg SendMail(string EmailName)
        {
            if (EmailName.EndsWith("@augurit.com") == false)
            {
                return new ResMsg() { MsgCode = "SendMail", IsOk = false, ErrorMsg = "不是奥格的邮箱" };
            }
            var random = new Random();
            var code = random.Next(1000, 9999).ToString();

            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
            msg.To.Add(EmailName);
            msg.From = new MailAddress("chenbiao.chenbiao@163.com", "AgCIM 技术攻关部内部资料访问", System.Text.Encoding.UTF8);
            /* 上面3个参数分别是发件人地址（可以随便写），发件人姓名，编码*/
            msg.Subject = "AgCIM 技术攻关部内部资料访问";//邮件标题    
            msg.SubjectEncoding = System.Text.Encoding.UTF8;//邮件标题编码    
            msg.Body = code;//邮件内容    
            msg.BodyEncoding = System.Text.Encoding.UTF8;//邮件内容编码    
            msg.IsBodyHtml = false;//是否是HTML邮件    
            msg.Priority = MailPriority.Normal;//邮件优先级    

            SmtpClient client = new SmtpClient();
            client.Credentials = new System.Net.NetworkCredential("chenbiao.chenbiao@163.com", "UIUVCPXYJFTESPDV"/*,"Tangsheng@123"*/);
            //在71info.com注册的邮箱和密码    
            client.Host = "smtp.163.com";
            object userState = msg;
            try
            {
                client.SendAsync(msg, userState);
                AddNewUser(EmailName, code);
                return new ResMsg() { MsgCode = "", IsOk = true };
            }
            catch (System.Net.Mail.SmtpException ex)
            {
                Logger.WriteLine("发送右键部分出错:" + ex.Message + ";" + ex.StackTrace);
                return new ResMsg() { MsgCode = "SendMail", IsOk = false, ErrorMsg = ex.Message };
            }
        }
        private void AddNewUser(string EmailName, string code)
        {
            Logger.WriteLine("发送邮件中:" + EmailName + ".." + code);
            SaveUserToDB(EmailName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), code, 5);
            for (var i = 0; i < MailListItem.Count; i++)
            {
                if (MailListItem[i].EmailName == EmailName)
                {
                    MailListItem[i].Code = code;
                    MailListItem[i].LastSendDate = DateTime.Now;
                    SaveUserList();
                    return;
                }
            }
            MailListItem.Add(new MailInfo()
            {
                EmailName = EmailName,
                Code = code,
                LastSendDate = DateTime.Now
            });
            SaveUserList();
        } 
        #endregion

        #region 保存用户
        private void SaveUserList()
        {
            try
            {
                StringBuilder stringBuilder = new StringBuilder();
                for (var i = 0; i < MailListItem.Count; i++)
                {
                    stringBuilder.AppendLine(MailListItem[i].EmailName + "," + MailListItem[i].Code + "," + MailListItem[i].LastSendDate.ToString("yyyy-MM-dd HH:mm:ss"));
                }
                System.IO.File.WriteAllText("D:\\Program Files\\SendMailServer\\lastUser.ini", stringBuilder.ToString());
            }
            catch (Exception err)
            {
                System.IO.File.WriteAllText("D:\\Program Files\\SendMailServer\\log.txt", "SaveUserList失败" + err.Message + "," + err.StackTrace);
            }
        } 
        public void SaveUserToDB(string userName, string registTime,string validCode,int validDays)
        {
            StringBuilder stringBuilder = new StringBuilder();
            Microsoft.Data.Sqlite.SqliteConnection conn = null;
            Microsoft.Data.Sqlite.SqliteCommand cmd = null;
            SqliteDataReader dr = null;
            try
            {
                using (conn = DatabaseHelper.BuildConnection())
                {
                    var searchSql = "select count(*) from studioUser where userName=\"" + userName + "\"";
                    cmd = new Microsoft.Data.Sqlite.SqliteCommand(searchSql, conn);
                    var or = cmd.ExecuteScalar();
                    Logger.WriteLine("用户存在验证中:" + or);
                    if (or.ToString()=="0")
                    {
                        Logger.WriteLine("用户不存在，插入");
                        string sql = "insert into studioUser(userName,registTime,validCode,validDays) values(";
                        sql += "\"" + userName + "\",";
                        sql += "\"" + registTime + "\",";
                        sql += "\"" + validCode + "\",";
                        sql += "" + validDays + ")";
                        Logger.WriteLine("用户不存在，插入Sql=" + sql);
                        cmd = new Microsoft.Data.Sqlite.SqliteCommand(sql, conn);
                        dr = cmd.ExecuteReader();
                    }
                    else
                    {
                        Logger.WriteLine("用户存在，更新");
                        string sql = "update studioUser set ";
                        sql += " registTime=\"" + registTime + "\",";
                        sql += " validCode=\"" + validCode + "\",";
                        sql += " validDays=" + validDays + "";
                        sql += " where userName=\"" + userName + "\"";
                        cmd = new Microsoft.Data.Sqlite.SqliteCommand(sql, conn);
                        dr = cmd.ExecuteReader();
                    }
                   
                }
            }
            catch (Exception err)
            {
                Logger.WriteLine("SaveUserToDB发生异常:" + err.Message + ";" + err.StackTrace);
            }
            finally
            {
                if (dr != null)
                {
                    dr.Close();
                }
                if (cmd != null)
                {
                    cmd.Dispose();
                }
                if (conn != null)
                {
                    conn.Close();
                    conn.Dispose();
                }
            }
        }
        #endregion

        #region 验证用户
        public bool ValidUser(string userName,string validCode)
        {
            var t1 = DateTime.Now;
            for (var i = MailListItem.Count - 1; i > -1; i--)
            {
                if ((t1 - MailListItem[i].LastSendDate).TotalDays > MailListItem[i].validDayss)
                {
                    MailListItem.RemoveAt(i);
                    continue;
                }
                if (MailListItem[i].EmailName == userName && MailListItem[i].Code == validCode)
                {
                    return true;
                }
            }
            return false;
        }
        #endregion
    }
}
